<template>
    <el-table ref="cartTable" :data="cartData" @selection-change="updateSelectedRows">
        <template #empty>
            <el-col><el-text>购物车为空</el-text></el-col>
            <el-col><el-link href="/home" type="primary">去选购蛋糕吧</el-link></el-col>
        </template>
        <el-table-column type="selection" width="100" />
        <el-table-column label="商品信息" width="700">
            <template #default="scope">
                <el-row>
                    <el-col :span="4">
                        <el-image style="width: 100px; height: 100px;" :src="scope.row.goods.cover" fit="cover">
                            <template #error>
                                <div class="image-slot" style="font-size: 30px;">
                                    <el-icon>
                                        <Picture />
                                    </el-icon>
                                </div>
                            </template>
                        </el-image>
                    </el-col>
                    <el-col :span="12" :offset="1">
                        <el-row><el-text truncated>
                                <el-tooltip class="box-item" :content="scope.row.goods.name" placement="top-start">
                                    {{ scope.row.goods.name }}
                                </el-tooltip>
                            </el-text></el-row>
                        <el-row><el-text truncated>{{ scope.row.type.name }}</el-text></el-row>
                        <el-row><el-text truncated>{{ scope.row.goods.name }}</el-text></el-row>
                    </el-col>
                </el-row>
            </template>
        </el-table-column>
        <el-table-column prop="goods.price" label="单价" width="120" />
        <el-table-column prop="num" label="数量" width="300" align="center">
            <template #default="scope">
                <el-input-number @change="updateSelectedRows(this.$refs.cartTable.getSelectionRows()); isUpdate = true;"
                    v-model="scope.row.cart.num" :precision="0" :min="1" :max="10" />
            </template>
        </el-table-column>
        <el-table-column label="小计" width="100">
            <template #default="scope">
                ￥{{ (scope.row.goods.price * scope.row.cart.num).toFixed(2) }}
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
            <template #default="scope">
                <el-button link type="primary" size="large" @click="deleteOne(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- <el-divider /> -->
    <el-row
        style="border: 1px solid var(--el-border-color);border-radius: 5px;display: flex;align-items: center; margin-top: 20px;">
        <el-checkbox v-model="selectAll" :indeterminate="isIndeterminate" @change="my_selectAll"
            :disabled="this.cartData.length === 0" label="全选" style="margin: auto 10px;" size="large" />
        <el-button plain @click="updateCart">
            更新购物车
        </el-button>
        <div style="flex-grow: 1;" />
        <el-text style="width: 150px;">已选择:
            <span style="color: var(--el-color-primary-dark-2);font:700 16px 微软雅黑;">{{ selectedRows.length }}</span>
            件商品</el-text>
        <el-text style="width: 120px;">合计：￥
            <span style="color: var(--el-color-primary-dark-2);font:700 16px 微软雅黑;">{{ (total).toFixed(2) }}</span>
        </el-text>
        <el-button type="primary" :disabled="selectedRows.length === 0" plain style="width: 100px;height: 55px;"
            @click="submitOrder">去结算</el-button>
    </el-row>
</template>

<script >
import { ElMessage } from 'element-plus';
import axios from 'axios';

axios.defaults.baseURL = '/api';


export default {
    data() {
        return {
            isUpdate: false,
            cartData: [
                // {
                //     "cart": {
                //         "cid": 1,
                //         "uid": 1,
                //         "gid": 1,
                //         "num": 1,
                //         "createTime": "2023-12-25T23:00:18",
                //         "updateTime": "2023-12-25T23:00:18",
                //         "status": 1
                //     },
                //     "goods": {
                //         "gid": 1,
                //         "tid": 1,
                //         "name": "草莓蛋糕",
                //         "cover": "img7.jpg",
                //         "image1": "\"\"",
                //         "image2": "\"\"",
                //         "price": 89.9,
                //         "intro": "商品描述",
                //         "stock": 80,
                //         "createTime": "2023-12-15T14:26:14",
                //         "updateTime": "2023-12-15T14:26:14",
                //         "status": 1
                //     },
                //     "type": {
                //         "tid": 1,
                //         "name": "水果系列",
                //         "createTime": "2023-12-15T14:26:45",
                //         "updateTime": "2023-12-15T14:26:45",
                //         "status": 1
                //     }
                // },
                // {
                //     "cart": {
                //         "cid": 2,
                //         "uid": 1,
                //         "gid": 2,
                //         "num": 3,
                //         "createTime": "2023-12-25T23:00:18",
                //         "updateTime": "2023-12-25T23:00:18",
                //         "status": 1
                //     },
                //     "goods": {
                //         "gid": 2,
                //         "tid": 1,
                //         "name": "榴莲蛋糕",
                //         "cover": "img8.jpg",
                //         "image1": "\"\"",
                //         "image2": "\"\"",
                //         "price": 109.9,
                //         "intro": "商品描述",
                //         "stock": 70,
                //         "createTime": "2023-12-15T15:00:33",
                //         "updateTime": "2023-12-15T15:00:33",
                //         "status": 1
                //     },
                //     "type": {
                //         "tid": 1,
                //         "name": "水果系列",
                //         "createTime": "2023-12-15T14:26:45",
                //         "updateTime": "2023-12-15T14:26:45",
                //         "status": 1
                //     }
                // }
            ],
            selectedRows: [],
            total: 0,
            selectAll: false,
            isIndeterminate: false,
        }
    },
    mounted() {
        this.getCart();
    },
    beforeUnmount() {
        if (this.isUpdate) this.saveCart();
    },
    methods: {
        getCart() {
            axios.get('/cart/' + this.$store.state.user.uid)
                .then(result => {
                    if (result.data.code === 1) {
                        this.cartData = result.data.data;
                    } else {
                        if (result.data.msg === 'Invalid_token') {
                            ElMessage.info("登录信息失效，请重新登录");
                            this.$store.state.isLogin = false;
                            this.$store.state.navActive = '/login';
                            this.$cookies.remove('token');
                        }
                        console.log(result);
                    }
                })
                .catch(err => {
                    console.log(err);
                })
        },
        updateSelectedRows(selection) {
            this.selectedRows = selection;
            this.total = 0;
            for (const k in selection) {
                this.total += +selection[k].goods.price * selection[k].cart.num
            }
            this.selectAll = selection.length === this.cartData.length ? true : false;
            this.isIndeterminate = selection.length !== 0 && !this.selectAll ? true : false;
        },
        submitOrder() {
            if (this.selectedRows.length === 0) {
                ElMessage.info("先选择商品再去结算吧");
                return;
            }

            let search = "?";
            search += "goodsData=" + JSON.stringify(this.selectedRows);

            this.$store.state.navActive = '/order' + search;
        },
        my_selectAll() {
            if ((this.selectedRows.length !== this.cartData.length) === this.selectAll) {
                this.$refs.cartTable.toggleAllSelection();
            }
        },
        deleteOne(index, row) {
            let arr = [];
            arr.push(row.cart.cid);
            axios.delete('/cart/' + arr)
                .then(result => {
                    if (result.data.code === 1) {
                        ElMessage.success("删除成功");
                        this.cartData.splice(index, 1);
                        // this.getCart();
                    }
                })
                .catch(err => {
                    console.log(err);
                    ElMessage.error("删除失败，异常错误");
                })
        },
        saveCart() {
            const data = []
            for (const k in this.cartData) {
                let cart = {
                    cid: this.cartData[k].cart.cid,
                    num: this.cartData[k].cart.num,
                };
                data.push(cart);
            }
            axios.put('/cart', data)
                .then(result => {
                    if (result.data.code === 1) {
                        ElMessage.info("已保存购物车信息");
                        return true;
                    }
                })
                .catch(err => {
                    console.log(err);
                })
            return false;
        },
        updateCart() {
            if (this.saveCart()) this.getCart();
        }
    }
}
</script>

<style>
.box-item {
    width: 1000px;
}

.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}
</style>